package com.lqs.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lqs.blog.mapper.ArticleMapper;
import com.lqs.blog.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ThreadService {
    @Autowired
    private ArticleMapper articleMapper;

    //期望此此操作在线程池 执行 不会影响主线程
    @Async("taskExecutor")
    public void updateArticleViewCounts(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();

        articleUpdate.setViewCounts(viewCounts + 1);//阅读量加1
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper();
        //update ms_article set view_counts = ? where id = ? and view_count=  ?
        updateWrapper.eq(Article::getId, article.getId());
        //设置一个 为了在多线程环境下 线程安全
        updateWrapper.eq(Article::getViewCounts, article.getViewCounts());

        articleMapper.update(articleUpdate, updateWrapper);

//        try {
//            Thread.sleep(5000);
//            System.out.println("更新完成了......");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }


    /**
     * 通过文章id更新评论数
     *
     * @param articleId
     */
    @Async("taskExecutor")
    public void updateArticleCommentCounts(Long articleId) {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getId, articleId);
        Article article1 = articleMapper.selectById(articleId);

        Article article = new Article();
        LambdaUpdateWrapper<Article> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Article::getId, articleId);

        article.setCommentCounts(article1.getCommentCounts() + 1);
        articleMapper.update(article, wrapper);
    }


}
